// pages/problemup/index.js
var api = require('../../utils/serve')
var app = getApp();
var moment = require('moment');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autosize: {
      maxHeight: 40,
      minHeight: 80,
      
    },
    userId: "",
    fileName: '',
    ossList: '',
    imagePathList: [],
    urlName1: [],
    urlName2: [],
    message:"",
    districtList: [], //省份下拉表
    provinceData: [],//省份数据
    districtListShow: false,//省份弹窗
    selectedGoods:[],
    startTime :'',//开始时间
    endTime :'',//结束时间
    timeSelet: 1,
        startTime: '',
        endTime: '',
        currentDate: new Date().getTime(),
        // minDate: new Date().getTime(),
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            }
            if (type === 'month') {
                return `${value}月`;
            }
            if (type === 'day') {
                return `${value}日`;
            }
            return value;
        },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(1);
    this.data.userId = wx.getStorageSync('userId')
    console.log( this.data.userId);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  
  //使用前图片上传
  chooseImg1() {
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const data = res.tempFiles
        that.setFile(data)

        that.getOssKeyword(data[0].fileName, data[0].tempFilePath)
        const arr = []
        const arr1 = []
        data.map((i) => {
          arr.push(i.fileName)
          arr1.push(i.tempFilePath)
        })
        that.setData({
          urlName1: [...that.data.urlName1, ...arr],
          imagePathList: [...that.data.imagePathList, ...arr1]
        })

      }
    })
  },
  handleCancle(e) {
    const idx = e.currentTarget.dataset.idx
    console.log(idx);
    this.data.imagePathList.splice(idx, 1);
    this.data.urlName1.splice(idx, 1)
    this.setData({
      urlName1: this.data.urlName1,
      imagePathList: this.data.imagePathList
    })

  },
//随机生成文件名 
setFile(data) {
  // 将wx.chooseImage返回的数据进行扩展
  data.map((item, index) => {
    // 通过路径截取文件后缀名
    const fileFormat = item.tempFilePath.substring(item.tempFilePath.lastIndexOf(".") + 1, item.tempFilePath.length);
    // wx.getFileSystemManager()小程序文件管理器api，可以将通过文件路径将其转换成64编码
    //   const fileManager = wx.getFileSystemManager();
    //   const base64 = fileManager.readFileSync(item.tempFilePath, 'base64');
    //   item.fileContent = base64;
    //   item.fileSize = item.size;
    // 通过时间获取随机13位随机数并且拼接文件后缀进行文件命名
    item.fileName = this.getFileName(13) + '.' + fileFormat;
    // 此处操作是用来进行选中图片显示的，只有这样拼接才能显示base64编码的路径
    // item.tempFilePath = `data:image/${fileFormat};base64,${base64}`;;

  })
  this.setData({
    // imagePathList: this.data.imagePathList.concat(dtempFilePath)
  });
  // 此处操作是用来将获取到的文件数据传递给父组件进行文件上传
  // this.triggerEvent('imageChange', this.data.fileList)
},
// 随机生成文件名
getFileName(m) {
  m = m > 13 ? 13 : m;
  var num = new Date().getTime();
  return num.toString().substring(13 - m);
},


// 获取oss参数
getOssKeyword(name, path) {
  // console.log(path)

  var blank=""
    var myDate = new Date();
    var year=myDate.getFullYear();
    var month=(myDate.getMonth() + 1 < 10 ? '0' + (myDate.getMonth() + 1) : myDate.getMonth() + 1);
    var date=myDate.getDate() < 10 ? '0' + myDate.getDate() : myDate.getDate();
    var hour=myDate.getHours() < 10 ? '0' + myDate.getHours() : myDate.getHours();
    var min=myDate.getMinutes() < 10 ? '0' + myDate.getMinutes() : myDate.getMinutes();
    var sec=myDate.getSeconds() < 10 ? '0' + myDate.getSeconds() : myDate.getSeconds();
    var key=blank.concat(year,"-",month,"-",date," ",hour,":",min,":",sec);
                        
  // const key = new Date().format("YYYY-MM-DD");
  api.get('/zkxj/basic/oss', {
    dir: key,
    filename: name
  }).then(res => {
    if (res.data.code === 0) {
      this.setData({ ossList: res.data.data })
      wx.uploadFile({
        url: 'https://oss.zhongkexiangjiu.cn/',
        filePath: path,
        name: 'file', // 必须填file。
        formData: {
          key: this.data.ossList.key,
          policy: this.data.ossList.policy,
          OSSAccessKeyId: this.data.ossList.accessId,
          signature: this.data.ossList.signature,

        },
        success: (res) => {
          if (res.statusCode === 204) {
            console.log('上传成功');
          }
        },
        fail: err => {
          console.log(err);
          wx.showToast({
            title: '上传失败，请重新上传',
            icon: 'error',
            duration: 1000,
            mask: true
          })
        }
      });
    }
  })
},
//确定上传 
submit() {
  const key = moment(new Date()).format("YYYY-MM-DD");
  const arr = []
  console.log(this.data.message);
  this.data.urlName1.map((i) => {
    i = key + '/' + i
    arr.push(i)
  })
 let b=arr.join(",")
   console.log(b);
   
   
  if (
    this.data.message
  ) {
    wx.request({
      url: app.globalData.url+'/zkxj/question/addanswer',
      data: {
        
        "comOrUser":0,
        "imageName": arr.join(","),
       "title":this.data.message,
       "checkStatus":0
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
          'token':wx.getStorageSync('token')
      },
      success: (res) => {
        if(res.data.code==0){
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 2000,
            mask: true
          })
        }
        // this.setData({
        //   count: res.data.count,
        // });
        // console.log(this.data.gooodlist);
      },
    })
  } else {
    wx.showToast({
      title: '请填写必填项',
      icon: 'error',
      duration: 1000,
      mask: true
    })
  }
},
 
 /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})